package com.example.ai.controller;

import com.example.ai.entity.UserEntity;
import com.example.ai.security.SecurityUtils;
import com.example.ai.service.RoommateService;
import com.example.ai.service.UserService;
import com.example.ai.service.dto.RoommateFaceDTO;
import com.example.ai.utils.ImageTools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author : zhayh
 * @date : 2021-4-24 20:17
 * @description :
 */

@RestController
@RequestMapping("/api")
public class FaceController {
    @Resource
    private RoommateService roommateService;
    @Resource
    private UserService userService;
    @Value("${application.file.diskpath}")
    private String diskPath;
    @Value("${application.file.fileurl}")
    private String fileUrl;

    @PostMapping("/roommates-face")
    public ResponseEntity roommateAiFace(MultipartFile imageFile) {
        if (imageFile == null) {
            return ResponseEntity.badRequest().body("请上传图片");
        }
        String imageBase64 = ImageTools.imageToBase64(imageFile);
        List<RoommateFaceDTO> result = roommateService.getFaces(imageBase64);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/file/head-image")
    public ResponseEntity updateHeadImage(MultipartFile imageFile) {
        if (imageFile == null) {
            return ResponseEntity.badRequest().body("请上传头像图片");
        }
        // 获取文件名
        String fileName = imageFile.getOriginalFilename();
        // 使用uuid生成新文件名
        String serverFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        String serverDiskPath = diskPath + serverFileName;
        try {
            // 保存文件
            imageFile.transferTo(new File(serverDiskPath));
            // 生成文件url访问地址
            String serverFileUrl = fileUrl + "/" + serverFileName;
            String login = SecurityUtils.getCurrentUserLogin().orElse(null);
            if (login != null) {
                // 更新头像
                UserEntity userEntity = userService.updateUserHeader(login, serverFileUrl);
                return ResponseEntity.ok(userEntity);
            }
            return ResponseEntity.badRequest().body("获取用户失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件传输出错");
        }
    }
}
